<template>
  <div>
    <el-button @click="dialogFormVisible = true">添加小区公告 <i class="el-icon-circle-plus-outline"></i></el-button>

    <el-dialog title="添加信息" @close="handleDialogClose" :visible.sync="dialogFormVisible">

      <el-form :model="form" :rules="rules" ref="rulesForm" label-width="100px" class="demo-ruleForm">

        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入公告的标题" clearable @clear="onSubmit(1)"></el-input>
        </el-form-item>


        <my-editor v-model="form.content" :server="uploadSever"></my-editor>

        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注（选填）" clearable @clear="onSubmit(1)"></el-input>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleContinue">确 定</el-button>
      </div>
    </el-dialog>


    <el-form :inline="true" :model="formInline" class="demo-form-inline">

      <el-form-item label="标题">
        <el-input v-model="formInline.title" placeholder="小区公告标题" clearable @clear="onSubmit(1)"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formInline.remark" placeholder="小区公告备注" clearable @clear="onSubmit(1)"></el-input>
      </el-form-item>

        <span class="demonstration">时间</span>
        <el-date-picker
            v-model="formInline.creatTime"
            type="date"
            placeholder="选择日期">
          :picker-options="pickerOptions"
        </el-date-picker>

      <el-form-item>
        <el-button type="primary" @click="onSubmit(1)">查询</el-button>
      </el-form-item>


    </el-form>



    <el-table
      :data="pageInfo.list" v-loading="loading"
      style="width: 100%"
      :row-class-name="tableRowClassName">
    <el-table-column
        prop="title"
        label="标题"
        width="250">
    </el-table-column>

    <el-table-column
        prop="creatTime"
        label="创建时间"
        :formatter="formatDate"
        width="250">
    </el-table-column>

    <el-table-column
        prop="remark"
        label="备注"
        width="250">
    </el-table-column>

    <el-table-column
        fixed="right"
        label="详情"
        width="250">
      <template slot-scope="scope">
        <el-button @click="selectByid(scope.row)" type="text" size="small">查看详情</el-button>
      </template>
    </el-table-column>
    <!-- 逻辑删除 -->
    <el-table-column
        fixed="right"
        label="操作"
        width="250">
      <template slot-scope="scope">
        <el-button @click="handleClick(scope.$index,scope.row)" type="text" size="small">更新</el-button>
        <el-button @click="handledelect(scope.$index,scope.row)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

    <el-dialog title="小区公告详情" :visible.sync="particulars">
      <div>
<!--        <p><span>小区公告详情:</span>{{listBy.content}}</p>-->
<!--        <div v-html="listBy.content"></div>-->
        <!--显示后端传过来的html标签，并加空值处理-->
        <div class="content-box" v-if="listBy?.content" v-html="listBy.content"></div>
        <div v-else class="content-box">暂无小区公告</div>
      </div>
    </el-dialog>

  <el-pagination class="pageNum"
       background
       layout="prev, pager, next"
       @current-change="handlePageNum"
       :current-page="pageInfo.pageNum"
       :page-size="pageInfo.pageSize"
       :total="pageInfo.total">
  </el-pagination>
  </div>
</template>
<script>
let admin = window.localStorage.getItem("admin")
let adminid = JSON.parse(admin)
let id = adminid.id;
import MyEditor from "@/components/MyEditor.vue";
export default {
  name: "Notice",
  components: {
    MyEditor,
  },
  filters: {//过滤器，时间格式调整
    formatDateTime(value) {
      if (!value) return '';
      const date = new Date(value);
      // 使用UTC方法，避免时区转换
      const year = date.getUTCFullYear();
      const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
      const day = date.getUTCDate().toString().padStart(2, '0');
      const hours = date.getUTCHours().toString().padStart(2, '0');
      const minutes = date.getUTCMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} `;
      /*  其实这里如果按yyyy-MM-dd HH:mm显示的话，后面的HH:mm为00:00，要想改为整除显示后端查出来的时间的话，
        要改后端配置为：spring.jackson.date-format=yyyy-MM-dd HH:mm
        这样按年月日查询就不行了，所以就让他显示到日就行
       */
    },
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  },
  data(){
    return {
      form:{
        id:'',//id
        title:'',//标题
        content:'',//内容
        creatBy:id,//创建用户id
        updateBy:'',//更新用户id
        creatTime:'',//创建时间
        remark:'',//备注
      },
      formInline:{
        title:'',
        remark:'',
        creatTime:'',
      },

      dialogFormVisible:false,
      pageInfo:{},
      loading: false,
      uploadSever:this.$basePath+'Notice/uploadSever',
      rules:{},
      particulars:false,
      listBy:{},


      pickerOptions: {
        disabledDate(time) {
          return false;//任何日期不禁用
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      //
      value1: '',//组件自带，别删
      value2: '',//组件自带，别删
    }
  },
  created() {
   this.onSubmit(1)
  },
  methods:{
    tableRowClassName({row,rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      }else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    handlePageNum(pageNum){
      this.onSubmit(pageNum)
    },
    onSubmit(pageNum) {
      this.loading = true;
      let params = {pageNum:pageNum};
      if(this.formInline.creatTime){
        const date = new Date(this.formInline.creatTime);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        this.formInline.creatTime = `${year}-${month}-${day}`;
      }
      this.$axios.post('Notice/list',this.formInline,{params:params}).then((res)=>{
        this.pageInfo = res.data.pageInfo;
        this.loading = false;
      })

    },
formatDate(row, column, cellValue){
  if (!cellValue) return '';
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
},
    handleContinue(){
      if(this.form.id){
        this.$axios.post('Notice/update', this.form).then((res)=>{
          this.onSubmit(1)
          this.dialogFormVisible=false;
        })
      }else {
        this.$axios.post('Notice/add',this.form).then((res)=>{
          this.onSubmit(1)
          this.form={}
          this.dialogFormVisible=false
        })
      }
    },
    handleDialogClose() {
      this.resetForm();
    },
    resetForm() {
      // if (this.form.content) {
      //   this.form.content = '';
      //   this.$forceUpdate();
      // }
      this.form = {
        id:'',//id
        title:'',//标题
        content:'',//内容
        creatBy:this.id,//创建用户id
        updateBy:'',//更新用户id
        creatTime:'',//创建时间
        remark:'',//备注
      };
    },
    selectByid(row){
      this.particulars = true
      this.$axios.get(`Notice/selectByid?id=${row.id}`).then((res)=>{
          this.listBy = res.data.notice;
      })

    },
    handledelect(index,row){
      this.$confirm('你真的要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('Notice/'+row.id).then((res)=>{
          this.onSubmit(1);
        })
      })
    },

    handleClick(index,row){
      this.dialogFormVisible = true;
      this.$axios.get("Notice/"+row.id).then((res)=>{
        this.form = res.data.notice
      })
    }
    // handleLook(row){
    //   this.dialogMode = 'view'
    //   this.dialogTitle = '报修详情'
    //   this.currentRow = JSON.parse(JSON.stringify(row));//深拷贝当前行数据，深拷贝就是创建一个新对象，但是内容同row一致，确保对话框中的操作不会直接影响列表中的数据
    //   // 确保userRepair对象存在
    //   if (!this.currentRow.userRepair) {
    //     this.currentRow.userRepair = {
    //       content: '',
    //       enable: false,
    //       userId: null
    //     }
    //   }
    //   this.dialogFormVisible = true
    // },
  }
}

</script>

<style>
.pageNum {
  display: flex;
  justify-content: center;
  padding: 30px;
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>